package com.njy.cloudalibaba.consumer.interceptor;

import com.njy.pojo.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * 用于发送RestTemplate请求添加header
 */
@Component
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
    private final static Logger LOGGER = LoggerFactory.getLogger(RestTemplateInterceptor.class);

    /**
     *从mdc中取出traceid放入RestTemplate请求中
     * 发送下游请求时header就会添加进去
     * @param httpRequest
     * @param bytes
     * @param clientHttpRequestExecution
     * @return
     * @throws IOException
     */
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        //LOGGER.info(MDC.get(Constant.TRACE_ID));
        String TRACE_ID = MDC.get(Constant.TRACE_ID);
      //  LOGGER.info("RestTemplateInterceptor--->"+TRACE_ID);
        if (!StringUtils.isEmpty(TRACE_ID)){
            httpRequest.getHeaders().add(Constant.TRACE_ID ,TRACE_ID);
        }
        ClientHttpResponse response = null;
        response = clientHttpRequestExecution.execute(httpRequest, bytes);
        return response;
    }
}
